package com.pro.xwt.rest.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pro.xwt.common.model.DFile;
import com.pro.xwt.common.model.DSharing;
import com.pro.xwt.common.service.DFileService;
import com.pro.xwt.common.service.DSharingService;
import com.pro.xwt.common.utils.Common;
import com.pro.xwt.rest.ResponseResult;

@Controller
@RequestMapping("/download")
public class DownloadController {

	@Autowired
	DSharingService dSharingService;
	@Autowired
	DFileService dFileService;

	
	/**
	 * 下载分享文件接口
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(method = { RequestMethod.GET }, value = "/{id}")
	@ResponseBody
	public Object down(@PathVariable String id, HttpServletResponse response,HttpServletRequest request) throws IOException {
		DSharing ds = dSharingService.findById(id);
		if (ds == null) {
			return ResponseResult.fail("分享文件不存在", ds);
		}
		int size = 1024;
		OutputStream ops = null;
		BufferedInputStream bis = null;
		Date shareEndTime = ds.getShareEndTime();
		String fileName = null;
		if (shareEndTime.getTime() >= new Date().getTime()) {
			DFile dFile = dFileService.findById(ds.getShareFileId());
			//response.setContentType("application/force-download");
			// 获取文件路径
			String address = Common.FILE_SAVE_BASEPATH+dFile.getStoragePath();
			try {
				File file = new File(address);
				
				response.setContentType("application/octet-stream");  
				 boolean isMSIE = isMSBrowser(request);  
				  if (isMSIE) {  
				                fileName = URLEncoder.encode(dFile.getName(), "UTF-8");  
				            } else {  
				                fileName = new String(dFile.getName().getBytes("UTF-8"), "ISO-8859-1");  
				            }
				//String fileName = URLEncoder.encode(dFile.getName(), "UTF-8");
				response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
				response.setContentLength((int) file.length());
				bis = new BufferedInputStream(new FileInputStream(file));
				ops = response.getOutputStream();
				byte[] byteArray = new byte[size];
				int temp = 0;
				while ((temp = bis.read(byteArray)) != -1) {
					ops.write(byteArray, 0, temp);
				}
				
			} catch (Exception e) {

			} finally {
				if (bis != null) {
					bis.close();
					bis = null;
				}
				if (ops != null) {
					ops.close();

				}

			}
			return ResponseResult.fail("下载成功", ds);

		}else{
			return ResponseResult.fail("分享链接过期", ds);
		}
	}
	
	   private static String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};  
		  
	    public static boolean isMSBrowser(HttpServletRequest request) {  
	        String userAgent = request.getHeader("User-Agent");  
	        for (String signal : IEBrowserSignals) {  
	            if (userAgent.contains(signal))  
	                return true;  
	        }  
	        return false;  
	    } 
	
}
